// Add User to Group Controller
// Add a user to a group

function getGroup(groupName) {
    
    return groups.getGroup(groupName);

}

function getOrCreateUser(userName) {
    var user = people.getPerson(userName);
    if (user === null) {
        return people.createPerson(userName);         
    }
    return user;
}

function addUserToGroup(groupName, userName) {

    var group = getGroup(groupName);
    var user = getOrCreateUser(userName);

    if (group) {
        try {
            group.addAuthority(userName);
        }
        catch (ex) {
            if (ex.toString().indexOf("DuplicateChildNodeNameException") > -1) {
                return {success: true, 
                        message: "User " + userName + " already added to " + groupName + "."};
            } else {                 
                return {success: false, message: "Error adding user: " + ex};
            }
        }
        return {success: true, 
                message: "User: " + userName + " added to " + groupName + "."};
    } else {
        return {success: false,
                message: "Group not found: " + groupName};
    } 

}

var groupName = args.groupName;
var userName = args.userName;

var result = addUserToGroup(groupName, userName);
model.message = jsonUtils.toJSONString(result);

